<template>
  <div>
    <!--1视图-->
    <el-form :inline="true" :rules="rules" ref="ruleForm"  :model="user" class="demo-form-inline">
      <el-form-item label="账号" prop="username">
        <el-input v-model="user.username" placeholder="账号"></el-input>
      </el-form-item><br>
      <el-form-item label="密码" prop="password">
        <el-input v-model="user.password" show-password placeholder="密码"></el-input>
      </el-form-item><br>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="user.code" placeholder="验证码"></el-input>
        <el-image :src="codeUrl" @click="getCode"></el-image>
      </el-form-item><br>
      <el-form-item>
        <el-button type="primary" @click="login('ruleForm')">登录</el-button>
      </el-form-item>
    </el-form>

  </div>

</template>

<script>
export default {
  name: "LoginView",
  data() {
    return {
      //2属性定义
      user:{},
      codeUrl:'',
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
        ],
      }
    }
  }, methods: {
    //3自定义方法
    getCode(){
      let t=new Date().getTime();
      let uid = sessionStorage.getItem("uid");
      this.user.uid=uid;
      this.axios.post("auth/checkClickNum?uid="+uid).then(res=>{
        if(res.data.code==200){
          this.codeUrl="http://localhost:9999/auth/createCode?t="+t+"&uid="+uid;
        }else {
          this.$message.error(res.data.msg);
        }
      })
    },
    login(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.axios.post("auth/login",this.user).then(res=>{
            if(res.data.code==200){
              this.$message.success(res.data.msg);
              sessionStorage.setItem("token",res.data.data);
              this.$router.push("/");
            }else{
              this.$message.error(res.data.msg);
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }, created() {
    //4.钩子函数
    this.getCode();
  }
}
</script>

<style scoped>

</style>